﻿@{
    ViewBag.Title = "ConfirmOrder";
    Layout = "~/Views/Shared/_Default.cshtml";
}
@section head{
<style type="text/css">
    .selectedaddress{
        background-color:rgb(214, 233, 198) !important;
    }
</style>
}
<div class="container-fluid" style="background-color: #fff;">
    <div class="page-header" style="border-top: 1px dotted #e2e2e2">
        <a id="snacks" name="snacks"></a>
        <h1 style="color: #892e65;">
            选择收货地址 <small></small>
        </h1>
    </div>
    <div class="widget-body" style="min-height: 620px; margin-bottom:5px;">
    @if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        List<CollegeShop.Infrastructure.Entities.Entity.Deliveryaddress> address = 
            (List<CollegeShop.Infrastructure.Entities.Entity.Deliveryaddress>)ViewBag.DeliveryAddress;
        <div id="addressbox" class="widget-main padding-4">
            <ul id="tasks" class="item-list ui-sortable">
            @if (address != null && address.Any())
            {
                foreach (var item in address)
                {
                <li class="item-orange clearfix @(ViewBag.Use>0?(item.ID == ViewBag.Use?"selectedaddress":""): item.isDefault ? "selectedaddress" : "")">
                    <label class="inline">
                        <input type="radio" data-Id="@item.ID" class="ace" name="selectedaddress" onclick="changeselectedaddress(this)" @(ViewBag.Use>0?(item.ID == ViewBag.Use?"checked=\"checked\"":""): item.isDefault ? "checked=\"checked\"" : "") />
                        <span class="lbl">&nbsp;&nbsp;@CollegeShop.Infrastructure.Component.Support.CollegeManager.getCollegeName() @item.saleUnit.SalesUnitName @item.Address </span>
                        <span class="lbl">&nbsp;&nbsp;联系电话： @item.LinkMan @item.LinkPhone</span>
                    </label>
                    <div class="pull-right action-buttons">
                        <a href="javascript:;" onclick="deleteaddressitem(@item.ID,this)" title="删除" class="red"><i class="icon-trash bigger-130"></i></a><span class="vbar">
                        </span><a href="javascript:;" onclick="setdefaultaddressitem(@item.ID,this)" @(item.isDefault ? "class=green btndefault" : " title=设为默认 class=grey")><i class="icon-flag bigger-130"></i></a>
                    </div>
                </li>
                }
            }
            else 
            {
                <li class="item-orange clearfix selectedaddress">
                    <label class="inline">
                        <span class="lbl">&nbsp;&nbsp;您还没有维护任何收获地址 </span>
                        <span class="lbl">&nbsp;&nbsp;</span>
                    </label>
                </li>
            }
            </ul>
        </div>
        <div class="widget-main padding-4">
            <a class="btn btn-primary" onclick="createaddress(this)" href="javascript:;">使用新地址</a>
        </div>
    }
        <form id="addressForm" class="form-horizontal" method="post" action="/home/newDeliveryAddress">
        <input type="hidden" name="items" value="@ViewBag.Items" />
        <input type="hidden" name="type" />
        <div id="newaddressbox" class="widget-main padding-4 @(HttpContext.Current.User.Identity.IsAuthenticated ? "hide" : "")" style="margin:10px; border:1px solid #ccc;">
                <div class="control-group">
                    <!-- Text input-->
                    <label class="control-label" for="input01">
                        <strong>收货人姓名：</strong></label>
                    <div class="controls">
                        <input type="text" placeholder="收货人姓名" id="txtLinkMan" name="LinkMan" 
                            class="input-xxlarge {required:true,cn:true}" />
                    </div>
                </div>
                <div class="control-group">
                    <!-- Text input-->
                    <label class="control-label" for="input01">
                        <strong>收获地址：</strong></label>
                    <div class="controls">
                        <select disabled="disabled" style="width:120px;">
                            <option>@CollegeShop.Infrastructure.Component.Support.CollegeManager.getCollegeName()</option>
                        </select> -
                        <select style="width:120px;" id="sltsaleunitID" name="saleunitID">
                        @{
                            List<CollegeShop.Infrastructure.Entities.Entity.Salesunit> units = ViewBag.Units;
                            if (units != null && units.Any())
                            {
                                foreach (var item in units)
                                {
                                    <option value="@item.ID">@item.SalesUnitName</option>
                                }
                            }
                            }
                        </select> -
                        <input type="text" name="dormitory" id="txtdormitory" class="{required:true,normalchar:true}" />
                    </div>
                </div>
                <div class="control-group">
                    <!-- Text input-->
                    <label class="control-label" for="input01">
                        <strong>联系电话：</strong></label>
                    <div class="controls">
                        <input type="text" placeholder="联系电话" id="txtLinkPhone" name="LinkPhone" 
                            class="input-xxlarge {required:true,phone:true}" />
                    </div>
                </div>
                @if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                <div class="control-group">
                    <label class="control-label">
                        &nbsp;</label>
                    <div class="controls">
                        <input type="button" id="btnsaveanddefault" class="btn btn-primary" value="使用并设为默认" />
                        <input type="button" id="btnuse" class="btn btn-success" value="保存并使用" />
                    </div>
                </div>
                }
        </div>
        </form>
        <!-- /widget-main -->
        <div class="widget-main padding-4">
           <div class="widget-box transparent">
				<div class="widget-header widget-header-flat">
					<h4 class="lighter">
						<i class="icon-bookmark-empty icon-2x"></i>
						结算
					</h4>
				</div>

				<div class="widget-body">
					<div class="widget-main padding-4">
						<div id="sales-charts"></div>
					</div><!-- /widget-main -->
				</div><!-- /widget-body -->
			</div>
            <div class="well">
                <h1 class="green smaller lighter">
                    支付方式</h1>
                <div class="block">
                    <label >
                        <input type="radio" checked="checked" class="ace">
                        <span class="lbl">&nbsp;&nbsp;送货上门，货到付款 </span>
                        <span style="font-style:inherit; font-size:11px; color:#40f; text-decoration:underline;" 
                            data-placement="right" data-html="false"
							data-trigger="hover"
							data-content="确定购买之后将立刻安排配送，挑战10分钟送达"
                            class="introdution">说明 <i class="icon-double-angle-right"></i></span>
                    </label>
                </div>
                <div class="block">
                    <label>
                        <span class="lbl">商品合计：<i class="bolder red" style="font-size:18px;">@ViewBag.TotalPrice.ToString("F2")</i> 元</span>
                    </label>
                </div>
                <div class="block">
                    <label>
                        <span class="lbl">- 配送费：<i class="bolder red" style="font-size:18px;">@(ViewBag.IsMember?(ViewBag.TotalPrice>=5?"0.00":"0.50"):ViewBag.TotalPrice>=7?"0.00":"0.50")</i> 元</span>
                        <span style="font-style:inherit; font-size:11px; color:#40f; text-decoration:underline;" 
                            data-placement="right" data-html="true"
							data-trigger="hover"
							data-content="注册会员5元以上免费配送<br/>非注册会员7元以上免费配送"
                        class="introdution">说明 <i class="icon-double-angle-right"></i></span>
                    </label>
                </div>
                <div class="block">
                    <label>
                        <span class="lbl">合&nbsp;&nbsp;&nbsp;&nbsp;计：<i class="bolder red" style="font-size:18px;">@((ViewBag.TotalPrice + (ViewBag.TotalPrice >=5?0:new decimal(0.5))).ToString("F2"))</i> 元</span>
                    </label>
                </div>
                <div class="block">
                    <input type="button" id="btnconfirm" class="btn btn-danger" value="确认购买" />
                    <a href="/" class="btn btn-warning">再看看</a>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="completebox" class="modal hide fade">
  <div class="modal-header header-color-blue2">
    <h3 style="color:#fff;">正在提交订单，请稍候</h3>
  </div>
  <div class="modal-body">
    <div class="row-fluid">
        <div class="span2" id="confirmicon"><i class="loading"></i> </div>
        <div class="span10" id="confirmmessage" style="font-size:18px;height:40px;line-height:40px;">
            正在加载订单详情....
        </div>
    </div>
  </div>
  <div class="modal-footer">
    <a href="javascript:;" id="btngoorderlist" class="btn btn-success disabled">
    @(HttpContext.Current.User.Identity.IsAuthenticated?"查看订单":"您未登陆")
    </a>
    <a href="javascript:;" id="btngoindex" class="btn btn-primary disabled">返回首页</a>
  </div>
</div>
@section tail{
   <script type="text/javascript" src="/scripts/jquery.validate.js"></script>
   <script type="text/javascript" src="/scripts/jquery.metadata.js"></script>
   <script type="text/javascript">
       var cart = getCookie('goodscart');
       if(!cart || cart.length == 0){
            delCookie('goodscart');
            window.location.href = "/";
            if ($.browser.msie && $.browser.version == 6) {
                window.event.returnValue = false;
            }
       }
       function changeselectedaddress(sender) {
           $(sender).parent().parent().siblings('li').each(function () {
               $(this).removeClass('selectedaddress');
           });
           $(sender).parent().parent().addClass('selectedaddress');
       }
       function deleteaddressitem(id,sender) {
           if (confirm('您确认要删除此收货地址吗？')) {
               $.ajax({
                   url: '/home/deletedeliveryitem/' + id,
                   success: function () {
                       if ($(sender).parent().siblings('label').children(':radio').attr('checked')) {
                           $(sender).parent().parent().siblings('li:eq(0)').children('label').children(':radio').trigger('click');
                       }
                       $(sender).parent().parent().remove();
                   }
               });
           }
       }
       function setdefaultaddressitem(id, sender) {
           if ($(sender).attr('class').indexOf('green') >= 0) {
               return;
           }
           if (confirm('您确认要将此收货地址设为默认吗？')) {
               $.ajax({
                   url: '/home/setdefaultdelivery/' + id,
                   success: function () {
                       $(sender).parent().parent().siblings('li').each(function () {
                           $(this).children('div').children('a:eq(1)').attr('class', 'grey');
                       });
                       $(sender).attr('class', 'green');
                   }
               });
           }
       }
       function createaddress(sender) {
           $(sender).parent().toggle();
           $('#newaddressbox').toggle();
       }
       function getWindowMaxWidth() {
           return Math.max($(document.body).width(), $(document).scroll().width());;
       }
       function getWindowMaxHeight() { 
           return Math.max($(document.body).height(), $(document).scroll().height());
       }
       function checkisValid(isLogin) {
           if (isLogin) {
                var isselected = $('input:radio[name="selectedaddress"]:checked').length;
                if(isselected == 0){
                    $('#addressbox').children().eq(0).before('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button><strong>您还没选择收货地址，请选择收回地址或新添加收货地址并保存后确认订单！</strong></div>');
                    return false;
                }
                return true;
           } else {
               return $('#addressForm').valid();
           }
       }
       function getDeliveryAddress(){
            var delivery='{';
            delivery+='"UserName":"ghost",';
            //delivery.UserName='ghost';
            delivery += '"SalesUnitID":"'+escape($('#sltsaleunitID').val())+'",';
            //delivery.SalesUnitID=$('#saleunitID').val();
            delivery += '"isDefault":"false",';
            //delivery.isDefault=false;
            delivery += '"Address":"'+escape($('#txtdormitory').val())+'",';
            //delivery.Address=$('#txtdormitory').val();
            delivery += '"LinkMan":"'+escape($('#txtLinkMan').val())+'",';
            //delivery.LinkMan=$('#txtLinkMan').val();
            delivery += '"LinkPhone":"'+escape($('#txtLinkPhone').val())+'"';
            //delivery.LinkPhone=$('#txtLinkPhone').val();
            delivery += '}';
            return delivery.toString();
       }
       $(function () {
           $('#addressForm').validate({
               errorClass: "help-inline",
               errorElement: "span",
               highlight: function (element, errorClass, validClass) {
                   $(element).parents('.control-group').addClass('error');
               },
               unhighlight: function (element, errorClass, validClass) {
                   $(element).parents('.control-group').removeClass('error');
               }
           });
           $('#btnsaveanddefault').click(function () {
               $('input[name="type"]').val('saveanddefault');
               $('#addressForm').submit();
           });
           $('#btnuse').click(function () {
               $('input[name="type"]').val('saveanduse');
               $('#addressForm').submit();
           });
           $('#btnconfirm').click(function () {
               var isValid = checkisValid(@HttpContext.Current.User.Identity.IsAuthenticated.ToString().ToLower());
               if (isValid) {
                   var newMask = jQuery('<div id=\'ipopbackground\'/>');
                   newMask.css({
                       position: 'absolute',
                       zIndex: '10',
                       width: getWindowMaxWidth() + 'px',
                       height: getWindowMaxHeight() + 'px',
                       top: '0px',
                       left: '0px',
                       background: '#ccc',
                       filter: 'alpha(opacity=40)',
                       opacity: '0.30'
                   });
                   $('body').append(newMask);
                   $('#completebox').modal({ backdrop: false });

                   $.ajax({
                    url:'/home/submitorder',
                    type:'post',
                    data:{
                        address:$('input:radio[name="selectedaddress"]:checked').attr('data-Id'),
                        items:escape('@ViewBag.Items'),
                        tempAddress:escape(getDeliveryAddress())
                    },
                    success:function(res){
                        if(res == 'ok'){
                            $('#confirmicon').html('<i class="icon-ok icon-2x green"></i>');
                            $('#confirmmessage').text('订单提交成功，我们将立刻为您安排配送！');
                            $('#btngoindex').removeClass('disabled').attr('href','/');
                            @if(HttpContext.Current.User.Identity.IsAuthenticated){
                                @:$('#btngoorderlist').removeClass('disabled').attr('href','/order/list');
                            }
                            delCookie('goodscart');
                        }else{
                            $('#confirmicon').html('<i class="icon-remove icon-2x red"></i>');
                            $('#confirmmessage').text(res);
                            $('#btngoindex').removeClass('disabled').attr('href','/');
                            $('#btngoorderlist').removeClass('disabled btn-success').addClass('btn-warning').text('重新提交订单').attr('href','/home/cart');
                        }
                    },
                    error:function(){
                        $('#confirmicon').html('<i class="icon-remove icon-2x red"></i>');
                        $('#confirmmessage').text('对不起，订单提交失败，请稍后重试！');
                    }
                   });
               }
           });

           $('.introdution').each(function () {
               $(this).popover();
           });
       });
   </script>
}
